package com.android.bookgarden.utli;

import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v4.content.PermissionChecker;

import com.android.bookgarden.BuildConfig;
import com.android.bookgarden.MyApplication;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class UriUtil {
    private UriUtil() {
    }

    public static Uri getUriFromFileProvider(@NonNull File file) {
        return FileProvider.getUriForFile(MyApplication.getInstance(),
                BuildConfig.APPLICATION_ID + ".file_provider",
                file);
    }

    public static Uri copy(@NonNull Context context, @NonNull Uri fromUri, @NonNull File toFile) {
        try (FileChannel source = ((FileInputStream) context.getContentResolver().openInputStream(fromUri)).getChannel();
             FileChannel destination = new FileOutputStream(toFile).getChannel()) {
            if (source != null && destination != null) {
                destination.transferFrom(source, 0, source.size());
                return UriUtil.getUriFromFileProvider(toFile);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean requireSDKInt(int sdkInt) {
        return Build.VERSION.SDK_INT >= sdkInt;
    }

    public static boolean checkPermissionGranted(Context context, String permission) {
        return PermissionChecker.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
    }
}
